package cn.hd01.web.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.hd01.repository.entity.Staff;
import cn.hd01.repository.entity.Store;
import cn.hd01.service.DictionaryService;
import cn.hd01.service.RoleService;
import cn.hd01.service.StaffService;
import cn.hd01.service.StoreService;
import cn.hd01.web.auth.Auth;
import cn.hd01.web.util.WebException;

@Controller
@RequestMapping("/staff")
@Auth
public class StaffController {
	@Autowired
	private StaffService staffService;

	@Autowired
	private DictionaryService dictService;

	@Autowired
	private StoreService storeService;

	@Autowired
	private RoleService roleService;

	@RequestMapping(method = RequestMethod.GET)
	public String userView(Model m) {
//		m.addAttribute("types", dictService.findByType(DictionaryType.STAFF));
		m.addAttribute("stores", storeService.findAll());
		return "staff";
	}

	@ResponseBody
	@RequestMapping(path = "/list", method = RequestMethod.GET)
	private Page<Staff> find(Staff u, @PageableDefault Pageable pageable) {
		return staffService.find(u, pageable);
	}

	@ResponseBody
	@RequestMapping(path = "/delete/{id}", method = RequestMethod.GET)
	private void delete(@PathVariable("id") Integer id) {
		staffService.delete(id);
	}

	@ResponseBody
	@RequestMapping(path = "/save", method = RequestMethod.POST)
	private void save(Staff staff) {
		if (staff.getId() == null && staffService.exists(staff.getPhone())) {
			throw new WebException(HttpStatus.BAD_REQUEST, "手机号已经存在");
		}

		Store store = storeService.findOne(staff.getStoreId());
		staff.setStoreName(store.getName());
		staffService.save(staff);
	}

}
